import {
  getUserId,
  getToken
} from "../../utils/storage";

Page({
  data: {
    name: '',
    familyName: '',
    date: '',
    minDate: '',
    morningActive: true,
    afternoonActive: false,
    timeList: [{
        time: '08:00',
        status: 'available',
        remaining: 5
      },
      {
        time: '08:30',
        status: 'available',
        remaining: 5
      },
      {
        time: '09:00',
        status: 'available',
        remaining: 5
      },
      {
        time: '09:30',
        status: 'available',
        remaining: 5
      },
      {
        time: '10:00',
        status: 'available',
        remaining: 5
      },
      {
        time: '10:30',
        status: 'available',
        remaining: 5
      },
      {
        time: '11:00',
        status: 'available',
        remaining: 5
      },
      {
        time: '11:30',
        status: 'available',
        remaining: 5
      },
      {
        time: '12:00',
        status: 'available',
        remaining: 5
      }
    ],
    selectedTime: '',
    userPhone: '',
    showTip: false,
    showRemainingTip: false,
    remainingTipText: ''
  },

  onLoad: function () {
    const userId = getUserId();
    console.log("当前用户ID:", userId);
    console.log('页面加载');
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);
    const formatDate = function (date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return year + '-' + month + '-' + day;
    };
    const minDate = formatDate(tomorrow);

    this.setData({
      minDate: minDate,
      date: minDate
    });

    console.log('初始化完成');
  },

  // 姓名输入
  bindNameInput: function (e) {
    this.setData({
      name: e.detail.value
    });
  },

  // 手机号输入
  bindPhoneInput: function (e) {
    this.setData({
      userPhone: e.detail.value
    });
  },

  // 家人姓名输入
  bindFamilyNameInput: function (e) {
    this.setData({
      familyName: e.detail.value
    });
  },

  // 日期选择
  bindDateChange: function (e) {
    const selectedDate = e.detail.value;
    const minDate = this.data.minDate;
    const selectedTime = new Date(selectedDate).getTime();
    const minTime = new Date(minDate).getTime();

    if (selectedTime < minTime) {
      wx.showToast({
        title: '只能选择明天及以后的日期',
        icon: 'none'
      });
      this.setData({
        date: minDate
      });
      return;
    }

    this.setData({
      date: selectedDate
    }, function () {
      this.data.morningActive ? this.switchToMorning() : this.switchToAfternoon();
    }.bind(this));
  },

  // 切换上午时段
  switchToMorning: function () {
    const morningTimes = ['08:00', '08:30', '09:00', '09:30', '10:00', '10:30', '11:00', '11:30', '12:00'];

    const timeList = morningTimes.map(time => ({
      time: time,
      status: 'available',
      remaining: 5
    }));

    this.setData({
      morningActive: true,
      afternoonActive: false,
      timeList: timeList,
      selectedTime: ''
    });
  },

  // 切换下午时段
  switchToAfternoon: function () {
    const afternoonTimes = ['12:30', '13:00', '13:30', '14:00', '14:30', '15:00', '15:30', '16:00', '16:30', '17:00', '17:30', '18:00'];

    const timeList = afternoonTimes.map(time => ({
      time: time,
      status: 'available',
      remaining: 5
    }));

    this.setData({
      morningActive: false,
      afternoonActive: true,
      timeList: timeList,
      selectedTime: ''
    });
  },

  // 选择时间段
  selectTime: function (e) {
    const time = e.currentTarget.dataset.time;
    const date = this.data.date;
    const timeList = this.data.timeList;

    const datetimeParam = `${date} ${time}`;
    const encodedParam = encodeURIComponent(datetimeParam);

    wx.showLoading({
      title: '查询剩余次数...'
    });

    wx.request({
      url: `http://localhost:8080/appointment/appointment/count/${encodedParam}`,
      method: 'GET',
      success: (res) => {
        wx.hideLoading();
        if (res.data && typeof res.data.count === 'number') {
          const bookedCount = res.data.count;
          const remaining = 5 - bookedCount;

          this.setData({
            showRemainingTip: true,
            remainingTipText: `剩余可预约次数：${remaining}`
          });
          setTimeout(() => {
            this.setData({
              showRemainingTip: false
            });
          }, 2000);

          const isAvailable = remaining > 0;

          const newTimeList = timeList.map(item => {
            if (item.time === time) {
              return {
                ...item,
                status: isAvailable ? 'selected' : 'disabled',
                remaining: remaining
              };
            } else if (item.status === 'selected') {
              return {
                ...item,
                status: 'available'
              };
            }
            return item;
          });

          this.setData({
            timeList: newTimeList,
            selectedTime: isAvailable ? time : ''
          });
        } else {
          wx.showToast({
            title: '查询失败，请重试',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络异常，查询失败',
          icon: 'none'
        });
      }
    });
  },

  // 格式化时间
  _formatDateTime: function () {
    const date = new Date();
    return [
      date.getFullYear(),
      this._padZero(date.getMonth() + 1),
      this._padZero(date.getDate())
    ].join('-') + ' ' + [
      this._padZero(date.getHours()),
      this._padZero(date.getMinutes()),
      this._padZero(date.getSeconds())
    ].join(':');
  },

  // 补零工具函数
  _padZero: function (num) {
    return num < 10 ? '0' + num : num;
  },

  // 手机号格式验证
  _isValidPhone: function (phone) {
    const reg = /^1[3-9]\d{9}$/;
    return reg.test(phone);
  },

  // 提交预约
  handleReserve: function () {
    const name = this.data.name;
    const userPhone = this.data.userPhone;
    const selectedTime = this.data.selectedTime;
    const familyName = this.data.familyName;
    const date = this.data.date;
    // 获取userId作为remark值
    const remark = getUserId();

    // 表单验证
    if (!name) return wx.showToast({
      title: '请输入预约人姓名',
      icon: 'none'
    });
    if (!userPhone) return wx.showToast({
      title: '请输入手机号',
      icon: 'none'
    });
    if (!this._isValidPhone(userPhone)) {
      return wx.showToast({
        title: '请输入正确的手机号格式',
        icon: 'none'
      });
    }
    if (!selectedTime) return wx.showToast({
      title: '请选择预约时间',
      icon: 'none'
    });

    wx.showLoading({
      title: '处理中...',
      mask: true
    });

    // 验证手机号是否已预约 → 提交预约
    this._checkMobile(userPhone)
      .then(function () {
        const appointmentTime = date + ' ' + selectedTime + ':00';
        return this._submitAppointment({
          name: name,
          mobile: userPhone,
          appointmentTime: appointmentTime,
          extend2: familyName,
          appointmentType: 0,
          status: 0,
          createdAt: this._formatDateTime(),
          remark: remark // 增加remark字段，值为userId
        });
      }.bind(this))
      .then(function () {
        this.data.morningActive ? this.switchToMorning() : this.switchToAfternoon();

        wx.hideLoading();
        wx.showToast({
          title: '预约成功',
          icon: 'success',
          success: function () {
            setTimeout(function () {
              wx.navigateTo({
                url: '/pages/myAppointment/MA'
              });
            }, 1500);
          }
        });
      }.bind(this))
      .catch(function (errMsg) {
        wx.hideLoading();
        wx.showToast({
          title: errMsg,
          icon: 'none'
        });
      });
  },

  // 检查手机号是否已预约
  _checkMobile: function (mobile) {
    return new Promise(function (resolve, reject) {
      wx.request({
        url: 'http://localhost:8080/appointment/appointment/checkMobile/' + mobile,
        method: 'GET',
        success: function (res) {
          if (res.data && res.data.msg === '该手机号已预约') {
            reject('该手机号已预约');
          } else if (res.data && res.data.msg === '该手机号未预约') {
            resolve();
          } else {
            reject('查询预约状态失败');
          }
        },
        fail: function () {
          reject('网络异常，请稍后重试');
        }
      });
    });
  },

  // 提交预约表单到后端
  _submitAppointment: function (formData) {
    const token = getToken()
    return new Promise(function (resolve, reject) {
      wx.request({
        url: 'http://localhost:8080/appointment/appointment',
        method: 'POST',
        data: formData,
        header: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`
        },
        success: function (res) {
          if (res.data && res.data.code === 200) {
            resolve();
          } else {
            reject(res.data && res.data.msg ? res.data.msg : '预约提交失败');
          }
        },
        fail: function () {
          reject('提交失败（网络错误）');
        }
      });
    });
  }

});